from flask import Flask, request, jsonify
from flask_cors import CORS
import pymysql.cursors
from collections import Counter
from collections import defaultdict
from cos import angle
connection = pymysql.connect(host='localhost',
                             user='root',
                             password='1234',
                             database='soft',
                             cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})

@app.route('/typeOfLimousine')
def typeOfLimousine():
    sql = " SELECT * FROM cars where type = '轿车' "
    cursor.execute(sql)
    result=cursor.fetchall()
    connection.commit()
    return result

@app.route('/typeOfSUV')
def typeOfSUV():
    sql = " SELECT * FROM cars where type = 'SUV' "
    cursor.execute(sql)
    result=cursor.fetchall()
    connection.commit()
    return result

@app.route('/typeOfMPV')
def typeOfMPV():
    sql = " SELECT * FROM cars where type = 'MPV' "
    cursor.execute(sql)
    result=cursor.fetchall()
    connection.commit()
    return result

@app.route('/BrandOfBaoma')
def BrandOfBaoma():
    sql = " SELECT * FROM cars where brand = '宝马' "
    cursor.execute(sql)
    result=cursor.fetchall()
    connection.commit()
    return result

@app.route('/BrandOfBenchi')
def BrandOfBenchi():
    sql = " SELECT * FROM cars where brand = '奔驰' "
    cursor.execute(sql)
    result=cursor.fetchall()
    connection.commit()
    return result

@app.route('/BrandOfBiyadi')
def BrandOfBiyadi():
    sql = " SELECT * FROM cars where brand = '比亚迪' "
    cursor.execute(sql)
    result=cursor.fetchall()
    connection.commit()
    return result

@app.route('/BrandOfDazhong')
def BrandOfDazhong():
    sql = " SELECT * FROM cars where brand = '大众' "
    cursor.execute(sql)
    result=cursor.fetchall()
    connection.commit()
    return result

@app.route('/BrandOfHongqi')
def BrandOfHongqi():
    sql = " SELECT * FROM cars where brand = '红旗' "
    cursor.execute(sql)
    result=cursor.fetchall()
    connection.commit()
    return result

@app.route('/BrandOfLuhu')
def BrandOfLuhu():
    sql = " SELECT * FROM cars where brand = '路虎' "
    cursor.execute(sql)
    result=cursor.fetchall()
    connection.commit()
    return result

@app.route('/BrandOfQirui')
def BrandOfQirui():
    sql = " SELECT * FROM cars where brand = '奇瑞' "
    cursor.execute(sql)
    result=cursor.fetchall()
    connection.commit()
    return result

@app.route('/BrandOfWoerwo')
def BrandOfWoerwo():
    sql = " SELECT * FROM cars where brand = '沃尔沃' "
    cursor.execute(sql)
    result=cursor.fetchall()
    connection.commit()
    return result

@app.route('/getlimousineMax')
# 柱状图
def getlimousineMax():
    sql = "SELECT * FROM cars WHERE type='轿车'"
    cursor.execute(sql)
    result = cursor.fetchall()
    infos = []
    for item in result:
        infos.append([item['brand'], item['maxprice']])
    # 初始化字典，key是品牌，value是该品牌的最大价格
    brand_maxprice = defaultdict(int)
    # 遍历数据，更新最大价格
    for item in infos:
        brand = item[0]
        maxprice = item[1]
        if maxprice > brand_maxprice[brand]:
            brand_maxprice[brand] = maxprice
    x = list(brand_maxprice.keys())
    y = list(brand_maxprice.values())
    return [x, y]


@app.route('/getlimousineMin')
def getlimousineMin():
    sql = "SELECT * FROM cars WHERE type='轿车'"
    cursor.execute(sql)
    result = cursor.fetchall()
    infos = []
    for item in result:
        infos.append([item['brand'], item['minprice']])
    # 初始化字典，key是品牌，value是该品牌的最小价格
    brand_minprice = {}
    # 遍历数据，更新最小价格
    for item in infos:
        brand = item[0]
        minprice = item[1]
        if brand not in brand_minprice or minprice < brand_minprice[brand]:
            brand_minprice[brand] = minprice
    x = list(brand_minprice.keys())
    y = list(brand_minprice.values())
    return jsonify([x, y])


@app.route('/getSUVMax')
# 柱状图
def getSUVMax():
    sql = "SELECT * FROM cars WHERE type='SUV'"
    cursor.execute(sql)
    result = cursor.fetchall()
    infos = []
    for item in result:
        infos.append([item['brand'], item['maxprice']])
    # 初始化字典，key是品牌，value是该品牌的最大价格
    brand_maxprice = defaultdict(int)
    # 遍历数据，更新最大价格
    for item in infos:
        brand = item[0]
        maxprice = item[1]
        if maxprice > brand_maxprice[brand]:
            brand_maxprice[brand] = maxprice
    x = list(brand_maxprice.keys())
    y = list(brand_maxprice.values())
    return [x, y]

@app.route('/getSUVMin')
def getSUVMin():
    sql = "SELECT * FROM cars WHERE type='SUV'"
    cursor.execute(sql)
    result = cursor.fetchall()
    infos = []
    for item in result:
        infos.append([item['brand'], item['minprice']])
    # 初始化字典，key是品牌，value是该品牌的最小价格
    brand_minprice = {}
    # 遍历数据，更新最小价格
    for item in infos:
        brand = item[0]
        minprice = item[1]
        if brand not in brand_minprice or minprice < brand_minprice[brand]:
            brand_minprice[brand] = minprice
    x = list(brand_minprice.keys())
    y = list(brand_minprice.values())
    return jsonify([x, y])

@app.route('/getMPVMax')
# 柱状图
def getMPVMax():
    sql = "SELECT * FROM cars WHERE type='MPV'"
    cursor.execute(sql)
    result = cursor.fetchall()
    infos = []
    for item in result:
        infos.append([item['brand'], item['maxprice']])
    # 初始化字典，key是品牌，value是该品牌的最大价格
    brand_maxprice = defaultdict(int)
    # 遍历数据，更新最大价格
    for item in infos:
        brand = item[0]
        maxprice = item[1]
        if maxprice > brand_maxprice[brand]:
            brand_maxprice[brand] = maxprice
    x = list(brand_maxprice.keys())
    y = list(brand_maxprice.values())
    return [x, y]

@app.route('/getMPVMin')
def getMPVMin():
    sql = "SELECT * FROM cars WHERE type='MPV'"
    cursor.execute(sql)
    result = cursor.fetchall()
    infos = []
    for item in result:
        infos.append([item['brand'], item['minprice']])
    # 初始化字典，key是品牌，value是该品牌的最小价格
    brand_minprice = {}
    # 遍历数据，更新最小价格
    for item in infos:
        brand = item[0]
        minprice = item[1]
        if brand not in brand_minprice or minprice < brand_minprice[brand]:
            brand_minprice[brand] = minprice
    x = list(brand_minprice.keys())
    y = list(brand_minprice.values())
    return jsonify([x, y])

@app.route('/predict')
def predict():
    X=[]
    brand = float(request.args.get('brand'))
    type = float(request.args.get('type'))
    gearbox = float(request.args.get('gearbox'))
    energy=float(request.args.get('energy'))
    displacement=float(request.args.get('displacement'))
    horsepower=float(request.args.get('horsepower'))
    cylinders=float(request.args.get('cylinders'))
    airinflow=float(request.args.get('airinflow'))
    fuel=float(request.args.get('fuel'))
    X.append(brand)
    X.append(type)
    X.append(gearbox)
    X.append(energy)
    X.append(displacement)
    X.append(horsepower)
    X.append(cylinders)
    X.append(airinflow)
    X.append(fuel)
    from predict import theta1
    from predict import theta2
    import numpy as np
    X=np.array(X)
    theta1=np.array(theta1)
    theta2 = np.array(theta2)
    return [str(X.dot(theta1)),str(X.dot(theta2))]


@app.route("/tuijian")
def tuijian():
    sql = "SELECT * FROM cars"
    cursor.execute(sql)
    result = cursor.fetchall()
    connection.commit()

    des = []
    brand = float(request.args.get('brand'))
    type = float(request.args.get('type'))
    gearbox = float(request.args.get('gearbox'))
    energy = float(request.args.get('energy'))
    displacement = float(request.args.get('displacement'))
    horsepower = float(request.args.get('horsepower'))
    cylinders = float(request.args.get('cylinders'))
    airinflow = float(request.args.get('airinflow'))
    fuel = float(request.args.get('fuel'))
    des.extend([brand, type, gearbox, energy, displacement, horsepower, cylinders, airinflow, fuel])

    brandMark = {"宝马": 1, "奔驰": 2, "比亚迪": 3, "大众": 4, "红旗": 5, "路虎": 6, "奇瑞": 7, "沃尔沃": 8}
    typeMark = {"轿车": 1, "SUV": 2, "MPV": 3}
    gearboxMark = {"手动": 1, "自动": 2}
    energyMark = {"汽油": 1, "新能源": 2, "轻混系统": 3}
    displacementMark = {"1.1-1.6L": 1, "1.7-2.0L": 2, "2.1-2.5L": 3, "2.6-3.0L": 4, "3.1-4.0L": 5, "4.0L以上": 6}
    horsepowerMark = {"101-150": 1, "151-200": 2, "201-250": 3, "251-300": 4, "301-400": 5, "400以上": 6}
    cylindersMark = {"3缸": 1, "4缸": 2, "6缸": 3, "8缸": 4, "8缸以上": 5}
    airinflowMark = {"自然吸气": 1, "涡轮增压": 2, "机械增压": 3}
    fuelMark = {"92号": 1, "95号": 2, "不使用": 3}

    carid = None
    for item in result:
        if (brandMark[item['brand']] == brand and
            typeMark[item['type']] == type and
            gearboxMark[item['gearbox']] == gearbox and
            energyMark[item['energy']] == energy and
            displacementMark[item['displacement']] == displacement and
            horsepowerMark[item['horsepower']] == horsepower and
            cylindersMark[item['cylinders']] == cylinders and
            airinflowMark[item['airinflow']] == airinflow and
            fuelMark[item['fuel']] == fuel):
            carid = item['id']
            break

    # 获取当前推荐项的描述
    arr = []
    for i, item in enumerate(result):
        if item['id'] != carid:
            nowdes = [
                brandMark[item['brand']],
                typeMark[item['type']],
                gearboxMark[item['gearbox']],
                energyMark[item['energy']],
                displacementMark[item['displacement']],
                horsepowerMark[item['horsepower']],
                cylindersMark[item['cylinders']],
                airinflowMark[item['airinflow']],
                fuelMark[item['fuel']]
            ]
            obj = {}
            a = angle(des, nowdes)
            obj["angle"] = a
            obj["name"] = item['name']
            arr.append(obj)

    arr.sort(key=lambda v: v["angle"], reverse=True)
    print(arr[:5])
    return jsonify(arr[:5])

app.run()
